<template>
  <el-dialog
    :title="title + '导入'"
    :visible.sync="dialogVisible"
    width="500px"
    customClass="mes_dialog upload_dialog"
    v-dialogDrag
    :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="step_one mes_file_secret"  v-if="step === 1">
      <div class="import_item">
        <div class="import_label"><span class="import_required">*</span>文档密级：</div>
        <div class=" import_cont">
          <el-select v-model="secrecyGrade" size="small" placeholder="请选择密级">
            <el-option
              v-for="item in fileSecretLevel"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="import_item">
        <div class="import_label"><span class="import_required">*</span>选择文件：</div>
        <div class=" import_cont file_cont">
          <div class="mes_btn">
            <el-button class="file_btn" @click="$refs.fileInput.click()">
              <i class="iconfont icon-btn_addnew"></i>
              <span>选择文件</span>
              <input type="file"
                     ref="fileInput"
                     class="file_input"
                     :accept="accept.toString()"
                     @change="fileChange">
            </el-button>
            <span class="accept_text">支持{{accept.join('、')}}格式</span>
          </div>
          <div class="file_name_input" v-show="fileData && fileData.name">
            <i class="el-icon-document"></i>
            <tooltip-txt :text="fileData && fileData.name"></tooltip-txt>
          </div>
        </div>
      </div>
    </div>
    <div class="step_two" v-else-if="step === 2">
      <span>文件上传中...</span>
      <div class="total_progress">
        <div class="current_progress" :style="{width: progress}">
          <span>{{progress}}</span>
        </div>
      </div>
    </div>
    <div class="step_three" v-else-if="step === 3">
      <div class="step_msg">
        <i class="iconfont icon-xiaoxitishi"></i>
        <span class="step_msg_txt">上传失败</span>
      </div>
    </div>
    <div class="step_four"
         v-else-if="step === 4"
         v-loading="true"
         element-loading-text="数据绑定中"
    ></div>
    <!--<div class="step_five" v-else-if="step === 5">
      <div class="step_msg">
        <i class="iconfont icon-xiaoxitishi"></i>
        <span class="step_msg_txt">导入设备失败{{errorContent ? ': ' + errorContent : ''}}</span>
      </div>
    </div>-->
    <div class="error_check" v-else-if="step === 5">
      <div class="step_msg" :class="{has_error_message: errorContent.length > 0, 'simple_message': errorContent.length === 0}">
        <i class="iconfont icon-xiaoxitishi"></i>
        <span class="step_msg_txt" v-if="errorContent.length > 0">导入{{title}}失败，请根据以下提示进行修改</span>
        <span class="step_msg_txt" v-if="errorContent.length === 0">导入{{title}}失败</span>
      </div>
      <div class="err_msg table_container" v-if="errorContent.length > 0">
        <el-table :data="errorContent" :show-header="false" border max-height="350">
          <el-table-column type="index" width="40" align="center"></el-table-column>
          <el-table-column style="height: 20px" show-overflow-tooltip
                           :resizable="false">
            <template slot-scope="scope">{{scope.row}}</template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="step_six" v-else-if="step === 6">
      <div class="step_msg">
        <i class="iconfont icon-zhengquetishi"></i>
        <span class="step_msg_txt">上传成功</span>
      </div>
    </div>
    <span slot="footer" class="mes_btn">
      <el-button type="primary" v-if="step === 1" @click="importFile">上传</el-button>
      <el-button type="primary" v-else-if="step === 3" @click="handleClose(true)">重新上传</el-button>
      <el-button type="primary" v-else-if="step === 5" @click="handleClose(true)">重新上传</el-button>
      <el-button type="primary" v-else-if="step === 6" @click="handleClose">确定</el-button>
      <el-button @click="handleClose" v-if="step !== 6">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'ResourceManageUpload',
  data() {
    return {
      // 是否显示弹框
      dialogVisible: false,
      // 上传token
      importToken: null,
      // 绑定设备token
      deviceToken: null,
      // 文件对象
      fileData: {},
      // 上传步骤
      step: 1,
      // 上传进度
      progress: '0%',
      // 文件密级
      secrecyGrade: this.defaultFileLevel,
      // 文件限制类型
      accept: ['.xls', '.xlsx'],
      // 文件错误内容
      errorContent: [],
      // 导入标题
      title: '',
      // 导入后保存路径
      saveUrl: ''
    }
  },
  computed: {
    // 文档密级字典
    fileSecretLevel() {
      return this.$store.state.dict.fileSecretLevel.labels || []
    }
  },
  methods: {
    // 打开弹框
    openDialog(title, saveUrl) {
      if (title && saveUrl) {
        this.title = title
        this.saveUrl = saveUrl
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.fileInput.value = null
        })
      }
    },
    // 关闭弹框
    handleClose(type) {
      switch (this.step) {
        case 1: case 6:
          this.dialogVisible = false
          this.secrecyGrade = this.defaultFileLevel
          this.clear()
          break
        case 3: case 5:
          if (type !== true) {
            this.dialogVisible = false
            this.secrecyGrade = this.defaultFileLevel
          }
          this.clear()
          break
        case 2:
          this.importToken.cancel('终止上传')
          this.step = 3
          break
        case 4:
          this.deviceToken.cancel('终止绑定')
          this.step = 5
          break
      }
    },
    // 清空重置
    clear() {
      this.fileData = {}
      this.importToken = null
      this.deviceToken = null
      this.progress = '0%'
      this.step = 1
    },
    // 选择文件
    fileChange(e) {
      let file = e.target.files[0]
      if (file && /^(\.xls)|(xlsx)$/.test(file.name.slice(-4).toLowerCase())) {
        this.fileData = file
        e.target.value = null
      } else if (file) {
        this.fileData = {}
        this.$message({
          type: 'error',
          message: `文件格式错误，请选择后缀为${this.accept.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      }
    },
    // 上传进度回调
    progressBar(progressEvent) {
      if (progressEvent.lengthComputable) {
        this.progress = parseInt(progressEvent.loaded / progressEvent.total * 100) + '%'
      }
    },
    // 点击上传
    importFile () {
      if (!this.secrecyGrade) {
        this.$message({
          type: 'error',
          message: '请先选择文档密级',
          duration: 1500,
          center: true
        })
      } else if (!this.fileData.name) {
        this.$message({
          type: 'error',
          message: `请先选择后缀为${this.accept.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      } else {
        this.step = 2
        this.importToken = this.$axios.CancelToken.source()
        let formdata = new FormData()
        formdata.append('file', this.fileData)
        formdata.append('fileSecretLevel', this.secrecyGrade)
        this.$store.dispatch('importFile', {
          data: formdata,
          onUploadProgress: this.progressBar,
          cancelToken: this.importToken.token,
        }).then(res => {
          this.step = 4
          this.saveData(res.filePath)
        }).catch(() => {
          this.step = 3
        })
      }
    },
    // 上传成功回调
    saveData(filePath) {
      this.deviceToken = this.$axios.CancelToken.source()
      let postData = {
        method: 'post',
        url: this.saveUrl,
        data: {
          path: filePath,
          fileName: this.fileData.name
        },
        cancelToken: this.deviceToken.token,
        noCommit: true
      }
      this.$store.dispatch('saveData', postData).then((res) => {
        let responseData = res.data
        if (Array.isArray(responseData) && responseData.length) {
          this.errorContent = responseData
          this.step = 5
        } else {
          this.step = 6
          this.$emit('importSuccess')
        }
      }).catch((res) => {
        this.step = 5
      })
    }
  }
}
</script>

<style scoped lang="less">
  .upload_dialog{
    .step_two {
      width: 100%;
      .total_progress {
        margin: 20px 0;
        width: 100%;
        height: 20px;
        background-color: @mesBgDefault;
        border-radius: 2px;
        overflow: hidden;
        .current_progress {
          height: 20px;
          background: url(./../../assets/img/bg_loading.png) top left;
          background-size: 100%;
          font-size: 12px;
          color: @mesFontWhite;
          line-height: 20px;
          text-align: right;
        }
      }
    }
    .step_msg {
      height: 24px;
      padding: 20px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      color: #333;
      .step_msg_txt {
        height: 16px;
        line-height: 16px;
      }
      .icon-zhengquetishi {
        color: @mesFontSuccess;
        font-size: 24px;
        margin-right: 5px;
      }
      .icon-xiaoxitishi {
        font-size: 24px;
        margin-right: 5px;
      }
    }
    .step_four{
      height: 90px;
    }
    .step_three,.step_five{
      .step_msg{
        color: @mesFontRed;
      }
    }
    .error_check {
      .step_msg {
        color: @mesFontRed;
        font-size: 14px;
        justify-content: flex-start!important;
        &.has_error_message{
          padding:0;
        }
        &.simple_message{
          display: flex;
          align-items: center;
          justify-content: center!important;
        }
        .icon-xiaoxitishi {
          font-size: 16px;
          margin-right: 3px;
        }
      }
    }
  }
</style>
<style lang="less">
  .error_check{
    .el-table td {
      padding: 0!important;
      height: 30px;
      line-height: 30px;
    }
    .el-table td:first-child .cell {
      padding: 0 5px;
    }
  }
</style>
